package com.gsit.ocrbatch.controller;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.apache.commons.lang.StringUtils;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Repository;
import org.springframework.ui.velocity.VelocityEngineUtils;

import com.gsit.ocrbatch.domain.EmailMessage;
import com.gsit.ocrbatch.domain.FileAttachment;
import com.gsit.ocrbatch.utils.EmailType;
import com.gsit.ocrbatch.utils.SendMailUtil;

@Repository
public class EmailProcesser extends Thread{
	
	private static final Logger logger = LoggerFactory.getLogger(EmailProcesser.class);
	
	private EmailMessage  message;
	
	@Autowired
	private JavaMailSender mailSender;
	
	@Autowired
	private SimpleMailMessage simpleMailMessage;
	
	@Autowired
	private  VelocityEngine velocityEngine;
	
	public void execute(EmailMessage  message)throws Exception{
		this.setName("EmailProcesser");
		this.message = message;
		this.start();
	}
	
	@Override
	public void run() {
		try {
			sendMail(message);
		} catch (ParseErrorException | MethodInvocationException
				| ResourceNotFoundException | IOException | MessagingException e) {
			e.printStackTrace();
		}
	}
	
	
	public void sendMail(final EmailMessage emailMessage)
			throws ParseErrorException, MethodInvocationException, ResourceNotFoundException, IOException, MessagingException {
		logger.info("Inside sendMail() with velocityTemplate : MailServiceImpl");
		//StringWriter emailBody = convertTemplateBodyToEmailBody(emailMessage.getEmailBody(),emailMessage.getTemplateVariables());
		
		StringWriter emailBody = convertTemplateBodyFromMailTemplate("/mail.vm",emailMessage.getTemplateVariables());
		//StringWriter emailBody = convertTemplateBodyFromMailTemplate(emailMessage.getEmailBody(),emailMessage.getTemplateVariables());
		
		MimeMessage message =createEmailMessage(emailMessage, emailBody.toString());
		
		logger.info("sending mail....");
		
		/*try {
			Thread t = new Thread(new SendMailUtil(emailMessage,mailSender,message));
			t.start();
		} catch (Exception e) {
			logger.error("Error in "+emailMessage.toString());
			logger.error(e.getMessage(),e);
			e.printStackTrace();
		}*/
		
		SendMailUtil  util = new SendMailUtil(emailMessage,mailSender,message);
		util.runEmail();
		
		//mailSender.send(message);
		logger.info("successfully sent mail....");
		
	}
	
	
	
	
	
	private StringWriter convertTemplateBodyFromMailTemplate(String templateFileName,
			Map<String, Object> templateVariables) throws IOException {
		
		logger.info("Inside convertTemplateBodyToEmailBody(): MailServiceImpl");
		
		StringWriter emailBody = new StringWriter();
			
		String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, templateFileName, templateVariables);
		emailBody.append(body);	
		
		System.out.println("The body is "+body);
		
		return emailBody;
	}
	
	
	

	
	

	
	
	private MimeMessage createEmailMessage(EmailMessage emailMessage,String emailBody) throws MessagingException {
		
		logger.info("Inside createEmailMessage(): MailServiceImpl");
		
		MimeMessage message = mailSender.createMimeMessage();
		
		MimeMessageHelper emailContent = new MimeMessageHelper(message, true);
		if(StringUtils.isNotBlank(emailMessage.getFrom())){
			System.out.println("The from mail id is "+emailMessage.getFrom());
			emailContent.setFrom(emailMessage.getFrom());
		}else{
			emailContent.setFrom(simpleMailMessage.getFrom());
		}
		emailContent.setTo(emailMessage.getReceipientList().toArray(new String[emailMessage.getReceipientList().size()]));
		emailContent.setSubject(emailMessage.getEmailSubject());
		
			for (FileAttachment fileAttachment : emailMessage.getAttachments()) {
				emailContent.addAttachment(fileAttachment.getFileName(), new ByteArrayResource(fileAttachment.getFileContents()));
			}
	
		if(EmailType.HTML==  emailMessage.getEmailType()){
			emailContent.setText(emailBody,true);	
		}else{
			emailContent.setText(emailBody);	
		}
		
		
		return message;
	}

}
